package org.languageguide.storage;

import java.sql.Connection;
import java.sql.SQLException;
import javax.servlet.ServletException;
import javax.sql.DataSource;

import javax.naming.InitialContext;
import javax.naming.Context;


public class DBConnector {

	private static DBConnector me;
	private DataSource _ds;
	private boolean usePool = true;
	private Connection connection;
	
	static {
		try {
			me = new DBConnector();
		} catch (ServletException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	

	private DBConnector() throws ServletException  {
		if (usePool){
			try {	
				Context ic = new InitialContext();	
				_ds = (DataSource) ic.lookup("java:comp/env/jdbc/mysql");
			} catch (Exception e) {
					throw new ServletException(e);
			}
		}
		else{
			
			
		}		
	}
	

	static public DBConnector getInstance() {
		return me;
	}

	public Connection getConnection(){
		if (usePool){
			try {
				System.out.println("connection get");
				return _ds.getConnection();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			return null;
		}
		else {
			return connection;
		}
	}
	
	public Connection getConnection(boolean usePoll){
		if (usePool){
			try {
				System.out.println("connection get");
				return _ds.getConnection();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			return null;
		}
		else {
			return connection;
		}
	}
	
	public void close(Connection connection){ // , Statement statement
		if (usePool){
			try {
				if (connection != null){
					connection.close();
					System.out.println("connection close");
				}
			
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		else{
			
		}
	}

}
